package com.qf.zuoye0620.controller;

import com.qf.zuoye0620.entity.LoginRequest;
import com.qf.zuoye0620.entity.LoginResponse;
import com.qf.zuoye0620.entity.RegisterRequest;
import com.qf.zuoye0620.entity.User;
import com.qf.zuoye0620.service.UserService;
import com.qf.zuoye0620.service.impl.UserServiceImpl;
import com.qf.zuoye0620.utils.JWTUtils;
import com.qf.zuoye0620.utils.PasswordUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.NoSuchAlgorithmException;

/**
 * @Author UNIQ7xi
 * @Date 2023/6/20 19:16
 * @Version v1.8
 **/
@RestController
@RequestMapping("/test")
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    @PostMapping("/test1")
    public ResponseEntity<?> login(@RequestBody LoginRequest request) throws NoSuchAlgorithmException {
        User user = userService.getUserByUsername(request.getUsername());
        if(user == null) {
            System.out.println("Username not found");
        }

        if(!PasswordUtils.verifyPassword(request.getPassword(), user.getPassword())) {
            System.out.println("Invalid username or password");
        }

        // 登录成功，返回Token
        String token = JWTUtils.generateToken(user.getId(), user.getUsername());
        return ResponseEntity.ok(new LoginResponse(token));
    }

    @PostMapping("/test2")
    public ResponseEntity<?> register(@RequestBody RegisterRequest request) throws NoSuchAlgorithmException {
        User existingUser = userService.getUserByUsername(request.getUsername());
        if(existingUser != null) {
            System.out.println("User already exists");
        }

        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(PasswordUtils.hashPassword(request.getPassword()));
        userService.save(user);


        // 注册成功，返回Token
        String token = JWTUtils.generateToken(user.getId(), user.getUsername());
        return ResponseEntity.ok(new LoginResponse(token));
    }
}
